#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 30   //
#define MAXLIST 100 //
#define MAXNAME 100 //

typedef struct index
{
	char id[4];
	struct index *next;
};
typedef struct key
{
	char *name;
	index *head;
};
typedef struct ID_list
{
	key list[MAXLIST];
	int num;
};

typedef struct word_list
{
	char word[MAXLIST][MAXLEN];
	int num;
};

word_list wl;
ID_list il;

// mark
int iskey(char key[])
{
	for (int i = 0; i < wl.num; i++)
	{
		if (strcmp(key, wl.word[i]) == 0)
			return 1;
	}
	return 0;
}

// mark
void insert(char id[], char name[])
{
	int i;
	for (i = 0; i < il.num; i++)
	{
		if (strcmp(il.list[i].name, name) == 0)
			break;
	}
	if (i == il.num)
	{
		il.list[il.num].name = (char *)malloc(sizeof(char) * strlen(name));
		il.list[il.num].head = NULL;
		strcpy(il.list[il.num].name, name);
		index *book_id = (index *)malloc(sizeof(index));
		strcpy(book_id->id, id);
		book_id->next = il.list[il.num].head;
		il.list[il.num].head = book_id;
		il.num++;
	}
	else
	{
		index *book_id = (index *)malloc(sizeof(index));
		strcpy(book_id->id, id);
		book_id->next = il.list[i].head;
		il.list[i].head = book_id;
	}
}

int main()
{
	/*******************code*******************/
	FILE *w, *b, *ind;
	if ((w = fopen("word", "r")) == NULL)
		exit(1);
	if ((b = fopen("books", "r")) == NULL)
		exit(1);
	if ((ind = fopen("index", "w")) == NULL)
		exit(1);
	wl.num = 0;
	il.num = 0;
	char str1[30];
	while (fscanf(w, "%29s", wl.word[wl.num]) == 1)
	{
		wl.num++;
	}
	char book_id[4];
	book_id[3] = '\0';
	char book_name[MAXNAME];
	while (fscanf(b, "%3s ", book_id) == 1)
	{
		fgets(book_name, 100, b);
		book_name[strlen(book_name) - 1] = '\0';
		//extract book_name
		int k = 0;
		while (book_name[k] != '\0')
		{
			char key[MAXLEN] = {'\0'};
			int i = 0;
			while (book_name[k] != ' ' && book_name[k] != '\0')
			{
				key[i++] = book_name[k++];
			}
			key[i] = '\0';
			if (!iskey(key))
				insert(book_id, key);
			if (book_name[k] == '\0')
				break;
			k++;
		}
	}

	//output
	for (int i = 0; i < il.num; i++)
	{
		fprintf(ind, "%s ", il.list[i].name);
		index *p = il.list[i].head;
		while (p)
		{
			fprintf(ind, "%s ", p->id);
			p = p->next;
		}
		fputs("\n", ind);
	}
	fclose(w);
	fclose(b);
	fclose(ind);
	/******************************************/
	printf("\n\n****************************\n");
	printf("Press Enter key to continue\n");
	getchar();
	return 0;
	/******************************************/
}
